<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Log;

use Monolog\Handler\StreamHandler;
use Monolog\Handler\SwiftMailerHandler;
use Monolog\Logger;
use Selibra\Command\Server;
use Selibra\Files\Config;
use Selibra\Tools\Console;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;

class Log
{

    const LOG_DEBUG = 'debug';
    const LOG_INFO = 'info';
    const LOG_NOTICE = 'notice';
    const LOG_WARNING = 'warning';
    const LOG_ERROR = 'error';
    const LOG_CRITICAL = 'critical';
    const LOG_ALERT = 'alert';
    const LOG_EMERGENCY = 'emergency';

    /**
     * @param mixed $logData 日志数据
     * @param string $level 日志等级
     */
    public static function record($logData, $level = self::LOG_DEBUG)
    {
        $debugBacktrace = debug_backtrace();
        $backtrace = reset($debugBacktrace);
        $backtraceArray = explode('/', $backtrace['file']);
        $file = end($backtraceArray);
        $logger = new Logger('main');
        $logger->pushHandler(new StreamHandler(Config::getRootPath() . '/Runtime/Logs/warning.log', Logger::WARNING));
        $logger->pushHandler(new StreamHandler(Config::getRootPath() . '/Runtime/Logs/error.log', Logger::ERROR));
//        $logger->pushHandler(new StreamHandler('php://stderr', Logger::DEBUG));

        // 获取邮件配置
        $emergencyConfig = \Selibra\Config\Config::get('application.log.emergency');
        if (!empty($emergencyConfig) && $emergencyConfig['type'] === 'email') {
            $fromEmailConfig = $emergencyConfig['formEmail'];
            // Create the Transport
            $transport = (new Swift_SmtpTransport($fromEmailConfig['host'], $fromEmailConfig['port'], $fromEmailConfig['encryption']))
                ->setUsername($fromEmailConfig['username'])
                ->setPassword($fromEmailConfig['password']);

            // Create the Mailer using your created Transport
            $mailer = new Swift_Mailer($transport);
            $message = (new Swift_Message('发生 EMERGENCY 错误!'))
                ->setFrom([$fromEmailConfig['username'] => $fromEmailConfig['name']])
                ->setTo(explode(',', $emergencyConfig['toEmail']))
                ->addPart($logData, 'text/html');

            $logger->pushHandler(new SwiftMailerHandler($mailer, $message, Logger::EMERGENCY));
        }

        $outputString = '[' . $file . '-' . $backtrace['line'] . 'Line] ';
        if ($logData instanceof \Throwable) {
            ob_start();
            echo $logData->getMessage() . PHP_EOL;
            echo $logData->getFile() . ' : ' . $logData->getLine() . PHP_EOL;
            echo $logData->getTraceAsString() . PHP_EOL;
            $logData = ob_get_clean();
        } elseif (is_object($logData) || is_array($logData)) {
            ob_start();
            var_dump($logData);
            $logData = ob_get_clean();
        }
        echo $logData . PHP_EOL;
        $logger->$level($logData . '  ' . $outputString);
    }

}
